// 轮播图功能
document.addEventListener('DOMContentLoaded', function() {
    // 轮播图初始化
    const initSlider = () => {
        const slides = document.querySelectorAll('.slides img');
        const controls = document.querySelectorAll('.slider-controls span');
        let currentIndex = 0;
        let interval;

        function showSlide(index) {
            slides.forEach((slide, i) => {
                slide.classList.toggle('active', i === index);
            });
            controls.forEach((control, i) => {
                control.classList.toggle('active', i === index);
            });
        }

        function nextSlide() {
            currentIndex = (currentIndex + 1) % slides.length;
            showSlide(currentIndex);
        }

        function startAutoSlide() {
            interval = setInterval(nextSlide, 3000);
        }

        // 控制点点击事件
        controls.forEach(control => {
            control.addEventListener('click', () => {
                clearInterval(interval);
                currentIndex = parseInt(control.dataset.index);
                showSlide(currentIndex);
                startAutoSlide();
            });
        });

        // 初始化
        showSlide(0);
        startAutoSlide();
    };

    // 购物车功能
    const initCart = () => {
        let cart = JSON.parse(localStorage.getItem('cart')) || [];

        function updateCartCount() {
            const count = cart.reduce((total, item) => total + item.quantity, 0);
            document.getElementById('cart-count').textContent = count;
        }

        function addToCart(productId) {
            const productCard = document.querySelector(`.add-to-cart[data-id="${productId}"]`).closest('.product-card');
            const product = {
                id: productId,
                name: productCard.querySelector('h3').textContent,
                price: parseFloat(productCard.querySelector('.price').textContent.replace('¥', '')),
                quantity: 1,
                image: productCard.querySelector('img').src
            };

            const existingItem = cart.find(item => item.id === productId);
            if (existingItem) {
                existingItem.quantity += 1;
            } else {
                cart.push(product);
            }

            localStorage.setItem('cart', JSON.stringify(cart));
            updateCartCount();
            alert(`已添加 ${product.name} 到购物车`);
        }

        // 绑定事件
        document.querySelectorAll('.add-to-cart').forEach(button => {
            button.addEventListener('click', function() {
                addToCart(this.dataset.id);
            });
        });

        updateCartCount();
    };

    

    // 初始化所有功能
    initSlider();
    initCart();
    //initSearch();
});